package cn.cs.service.impl;

import cn.cs.App;
import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.pojo.*;
import cn.cs.service.RepOrderService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.jms.ObjectMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class RepOrderServiceImpl implements RepOrderService{
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RestRepOrderClient client;

    @Resource
    private RestRepairOrderClient restRepairOrderClient;
    @Resource
    private RestClientUserClient restClientUserClient;

    @Resource
    private RestAppOrderClient appOrderClient;
    @Autowired
    private LogUtils logUtils;
    /***
     * 接收生成订单的消息
     * @param message
     */
    @RabbitListener(queues = Constants.RabbitQueueName.TO_QD_QUEUE)
    public void receiveOrderQueue(BookOrderMessageVo bookOrderMessageVo, Message message, Channel channel)throws Exception {
        logUtils.i("Consumer收到的报文为:",bookOrderMessageVo.getBookId());
        ObjectMessage objMsg = (ObjectMessage) message;
        try {
            //开始生成订单 TODO判断异常进行回滚
            Dto dto =   createOrder(bookOrderMessageVo);//判断成功失败
            if("true".equals(dto.getSuccess())){
                //向微信客户发送微信模板消息
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("orderId",dto.getData());
                HttpUtil.doPost("https://www.zzzsyh.com/cs_pay/send_template",map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                //消费者处理业务出现异常时，将消息放到死亡队列
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public Dto createOrder(BookOrderMessageVo bookOrderMessageVo) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>();
        String id = IdWorker.getId();
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            RepOrder order = new RepOrder();
            order.setId(id);
            order.setApp_order_id(bookOrderMessageVo.getBookId());
            order.setCreateTime(format.format(new Date()));
            order.setUser_id(bookOrderMessageVo.getUserId());
            order.setOrder_state(String.valueOf(Constants.OrderStatus.TOPAY));
            order.setRep_user_id(bookOrderMessageVo.getWorkerId());
//            setOrderStatus(bookOrderMessageVo);//修改抢购状态为获得订单待支付状态
            client.insertRepOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常", "002");
        }
        return DtoUtil.returnDataSuccess(id);
    }

    @Override
    public Dto getAllrepOrders(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","0001");
        }
        String state= request.getParameter("state");
        List<RepOrder> orders = new ArrayList<RepOrder>();
        Map<String,Object> parm = new HashMap<String, Object>();
        if(EmptyUtils.isNotEmpty(state)){
            parm.put("order_state",state);
        }
        parm.put("id",user.getId());
        orders =client.getAllRepOrders(parm);
        if(!EmptyUtils.isEmpty(orders)){
            return  DtoUtil.returnDataSuccess(orders);
        }else{
            return DtoUtil.returnFail("没有查询到任何订单","002");
        }
    }

    @Override
    public Dto getOrderInfoById(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String id = request.getParameter("orderId");
        RepOrder order = client.getRepOrderById(id);
        if(EmptyUtils.isNotEmpty(order)){
            Map<String,Object> param = new HashMap<String, Object>();
            param.put("orderId",id);
            param.put("type","2");
            List<RepProduct> proList = client.getRepProsByOrderId(param);
//            String userAddressId = order.get("user_address_id").toString();
//            String fulladdress = appOrderMapper.getUserFullAddressByid(userAddressId);
//            order.put("user_address",fulladdress);
            order.setPros(proList);
            return  DtoUtil.returnDataSuccess(order);
        }else{
            return DtoUtil.returnFail("没有查到此订单","002");
        }
    }

    @Override
    public Dto getAllrepEva(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","0001");
        }
        List<Map<String,Object>> evals = client.getAllrepEva(user.getId());
//        List<Map<String,Object>> evals = repOrderMapper.getAllrepEva("1");
        if(!EmptyUtils.isEmpty(evals)){
            int  average  = 0; int allSco = 0;
            for(Map<String,Object> map : evals){
                allSco = allSco + Integer.valueOf(map.get("score").toString());
            }
            average = allSco/evals.size();
            Map<String,Object> dataMap = new HashMap<String, Object>();
            dataMap.put("average",average);
            dataMap.put("evals",evals);
            dataMap.put("allSco",allSco);
            return  DtoUtil.returnDataSuccess(dataMap);
        }else{
            return DtoUtil.returnFail("没有查询到任何评价","002");
        }
    }

    @Override
    public Dto addRepProduct(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        //data={"orderId":"001","products":[{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"},{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"},{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"}]}
        String data = request.getParameter("data");
        JSONObject jso = JSONObject.parseObject(data);
        DecimalFormat df = new DecimalFormat("#.00");
        String  peopleCostJs= jso.getString("peopleCost");
        JSONArray array = jso.getJSONArray("products");
        JSONArray updateArray = jso.getJSONArray("up_products");
        String orderId  = jso.get("orderId").toString();
        RepOrder repOrder = client.getRepOrderById(orderId);
        AppOrder appOrder = appOrderClient.getAppOrderById(repOrder.getApp_order_id());
        if(EmptyUtils.isNotEmpty(repOrder) && EmptyUtils.isNotEmpty(appOrder)){
            if(EmptyUtils.isNotEmpty(appOrder.getIs_protect())){
                if("0".equals(appOrder.getIs_protect())){
                    String phone = appOrder.getUser_phone();
                    ClientUser clientUser = restClientUserClient.getClientUserByPhone(phone);
                    if(EmptyUtils.isEmpty(clientUser)){
                        return  DtoUtil.returnFail("客户未关注公众号，暂不能推送账单，请提醒客户使用手机号："+phone+"关注微信公众号","002");
                    }
                }
            }
            if("6".equals(appOrder.getOrder_state()) || "7".equals(appOrder.getOrder_state())){
                return  DtoUtil.returnFail("此服务单不是可生成账单状态，请刷新","002");
            }
        }else{
            return  DtoUtil.returnFail("没有找到此订单","002");
        }
        double cose = 0;
        if(EmptyUtils.isNotEmpty(appOrder.getFixed_price())){
            if(!"0.00".equals(appOrder.getFixed_price())){
                cose = Double.valueOf(appOrder.getFixed_price());
            }else{
                cose = Double.valueOf(peopleCostJs);
            }
        }else{
            cose = Double.valueOf(peopleCostJs);
        }

        if(EmptyUtils.isNotEmpty(updateArray)){
            for(int n = 0;n<updateArray.size();n++){
                JSONObject js = updateArray.getJSONObject(n);
                RepProduct repProduct = new RepProduct();
                repProduct.setId(IdWorker.getId());
                repProduct.setProduct_name(js.getString("name"));
                repProduct.setProduct_type_id(js.getString("type_id"));
                if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                    repProduct.setQrcode(js.getString("qrcode"));
                }
                repProduct.setProduct_model(js.getString("product_model"));
                repProduct.setCount(js.getString("count"));
                repProduct.setType("2");
                repProduct.setOrder_id(orderId);
                client.insertRepProduct(repProduct);

                QrHistory qrHistory = new QrHistory();
                qrHistory.setId(IdWorker.getId());
                qrHistory.setNode_code("gh");
                qrHistory.setOperation("损坏更换");
                qrHistory.setOperation_user_id(user.getId());
                qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                    qrHistory.setQrcode(js.getString("qrcode"));
                    client.insertQrHistory(qrHistory);
                }
            }
        }
        if(EmptyUtils.isNotEmpty(array)) {
            if(EmptyUtils.isNotEmpty(appOrder.getFixed_price())){
                if(!"0.00".equals(appOrder.getFixed_price())){
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject js = array.getJSONObject(i);
                        RepProduct repProduct = new RepProduct();
                        repProduct.setId(IdWorker.getId());
                        repProduct.setProduct_name(js.getString("name"));
                        repProduct.setProduct_type_id(js.getString("type_id"));
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            repProduct.setQrcode(js.getString("qrcode"));
                        }
                        repProduct.setProduct_model(js.getString("product_model"));
                        repProduct.setCount(js.getString("count"));
                        repProduct.setType("2");
                        repProduct.setOrder_id(orderId);
                        client.insertRepProduct(repProduct);
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            QrHistory qrHistory = new QrHistory();
                            qrHistory.setId(IdWorker.getId());
                            qrHistory.setQrcode(js.getString("qrcode"));
                            qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_code("az");
                            qrHistory.setOperation("安装");
                            qrHistory.setOperation_user_id(user.getId());
                            client.insertQrHistory(qrHistory);
                        }
                    }
                }else{
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject js = array.getJSONObject(i);
                        RepProduct repProduct = new RepProduct();
                        repProduct.setId(IdWorker.getId());
                        repProduct.setProduct_name(js.getString("name"));
                        repProduct.setProduct_price(js.get("price").toString());
                        repProduct.setProduct_name(js.getString("name"));
                        repProduct.setProduct_type_id(js.getString("type_id"));
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            repProduct.setQrcode(js.getString("qrcode"));
                        }
                        repProduct.setProduct_model(js.getString("product_model"));
                        repProduct.setCount(js.getString("count"));
                        repProduct.setType("2");
                        repProduct.setOrder_id(orderId);
                        cose = cose + (Double.valueOf(js.getString("price")) * Double.valueOf(js.get("count").toString()));
                        client.insertRepProduct(repProduct);
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            QrHistory qrHistory = new QrHistory();
                            qrHistory.setId(IdWorker.getId());
                            qrHistory.setQrcode(js.getString("qrcode"));
                            qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_code("az");
                            qrHistory.setOperation("安装");
                            qrHistory.setOperation_user_id(user.getId());
                            client.insertQrHistory(qrHistory);
                        }
                    }
                }
            }
            else{
                for (int i = 0; i < array.size(); i++) {
                    JSONObject js = array.getJSONObject(i);
                    RepProduct repProduct = new RepProduct();
                    repProduct.setId(IdWorker.getId());
                    repProduct.setProduct_name(js.getString("name"));
                    repProduct.setProduct_price(js.get("price").toString());
                    repProduct.setProduct_name(js.getString("name"));
                    repProduct.setProduct_type_id(js.getString("type_id"));
                    if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                        repProduct.setQrcode(js.getString("qrcode"));
                    }
                    repProduct.setProduct_model(js.getString("product_model"));
                    repProduct.setCount(js.getString("count"));
                    repProduct.setType("2");
                    repProduct.setOrder_id(orderId);

//                    Map<String, Object> map = new HashMap<String, Object>();
//                    String id = IdWorker.getId();
//                    map.put("id", id);
//                    map.put("product_name", js.get("name"));
//                    float f = Float.valueOf(js.get("price").toString());
//                    map.put("product_price", f);
//                    map.put("product_type_id", js.get("type_id"));
//                    if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
//                        map.put("qrcode", js.get("qrcode"));
//                    }
//                    map.put("product_model", js.get("product_model"));
//                    map.put("count", js.get("count"));
//                    map.put("type", "2");
//                    map.put("order_id", orderId);
                    cose = cose + (Double.valueOf(js.getString("price")) * Double.valueOf(js.get("count").toString()));
                    client.insertRepProduct(repProduct);
                    if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
//                        Map<String,Object> hisMap = new HashMap<String, Object>();
//                        String hisId = IdWorker.getId();
//                        hisMap.put("id",hisId);
//                        hisMap.put("operation","安装");
//                        hisMap.put("operation_user_id",user.getId());
//                        hisMap.put("node_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
//                        hisMap.put("node_code","az");
//                        hisMap.put("qrcode",js.get("qrcode"));
//                        hisMap.put("update_time",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

                        QrHistory qrHistory = new QrHistory();
                        qrHistory.setId(IdWorker.getId());
                        qrHistory.setQrcode(js.getString("qrcode"));
                        qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        qrHistory.setNode_code("az");
                        qrHistory.setOperation("安装");
                        qrHistory.setOperation_user_id(user.getId());
                        client.insertQrHistory(qrHistory);
                    }
                }
            }

        }
        BigDecimal decimalCost = new BigDecimal(cose);
        BigDecimal all_cost = decimalCost.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        repOrder.setAll_cost(all_cost.toString());
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("rep_user_id",user.getId());
        param.put("begin_time",DateUtil.format(new Date(),"yyyy-MM-dd")+" 00:00:00");
        param.put("end_time",DateUtil.format(new Date(),"yyyy-MM-dd hh:mm:ss"));
        Map<String,Object> parammap = client.getRepairPercentage();
        String cityS =  parammap.get("proportionCity").toString();
        String provinceS =  parammap.get("proportionProvince").toString();
        String platformS =  parammap.get("proportionPlatform").toString();
        double cityD = cose * Double.valueOf(cityS) ;
        BigDecimal decimalCit = new BigDecimal(cityD);
        BigDecimal cityB = decimalCit.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        repOrder.setEarCity(cityB.toString());
        double provinceD = cose * Double.valueOf(provinceS) ;
        BigDecimal decimalPro = new BigDecimal(provinceD);
        BigDecimal provinceB = decimalPro.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        repOrder.setEarProvince(provinceB.toString());
        double platformD = cose * Double.valueOf(platformS) ;
        BigDecimal decimalPla = new BigDecimal(platformD);
        BigDecimal platformB = decimalPla.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        repOrder.setEarPlatform(platformB.toString());
        double n = cose - cityD - provinceD - platformD ;
        BigDecimal decimal = new BigDecimal(n);
        BigDecimal setScale = decimal.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        BigDecimal coin =new BigDecimal(0.06).setScale(2,BigDecimal.ROUND_HALF_DOWN);
        BigDecimal porintSix = all_cost.multiply(coin).setScale(2,BigDecimal.ROUND_HALF_DOWN);
        String earning = setScale.subtract(porintSix).setScale(2,BigDecimal.ROUND_HALF_DOWN).toString();
        repOrder.setTax(porintSix.toString());
        repOrder.setEarning(earning);
        if(EmptyUtils.isNotEmpty(peopleCostJs)){
            repOrder.setPeopleCost(df.format(Float.valueOf(peopleCostJs)));
        }else{
            repOrder.setPeopleCost("0");
        }
        repOrder.setOrder_state("2");
        int m = client.updateRepOrder(repOrder);
        appOrder.setOrder_state("3");
        appOrderClient.updateAppOrder(appOrder);
                if(m>0){
                    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                            request.getSession().getServletContext());
                    // 判断是否有文件上传
                    if (multipartResolver.isMultipart(request)){
                        List<UploadInfo> list = null;
                        try {
                            list = UploadUtil.uploadFiles(request,"","order/orderBillImg/"+orderId);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        for(UploadInfo info :list){
                            Map<String,Object> map = new HashMap<String, Object>();
                            map.put("id",IdWorker.getId());
                            map.put("rep_order_id",orderId);
                            map.put("img","https://www.zzzsyh.com/image/order/orderBillImg/"+orderId+"/"+info.getOldName());
                            map.put("create_time",new Date());
                            client.insertOrderBillImg(map);
                        }
                    }
                }
                Map<String,Object> map =new HashMap<String, Object>();
                map.put("repOrderId",orderId);
                HttpUtil.doPost("https://www.zzzsyh.com/cs_pay/sendBill",map);
        return DtoUtil.returnSuccess();
    }

    @Override
    public Dto createBill(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String data = request.getParameter("data");
        JSONObject jso = JSONObject.parseObject(data);
        DecimalFormat df = new DecimalFormat("#.00");
        String  peopleCostJs= df.format(Float.valueOf(jso.getString("peopleCost")));//工时费
        String productCost = "";//配件费
        String prodcutComment ="";//配件说明
        String type= jso.get("type").toString();
        String orderId  = jso.get("orderId").toString();
        RepOrder repOrder = client.getRepOrderById(orderId);
        AppOrder appOrder = appOrderClient.getAppOrderById(repOrder.getApp_order_id());
        if("1".equals(type)){
//            Map<String,Object>testRep =new HashMap<String, Object>();
//            testRep.put("id",IdWorker.getId());
//            testRep.put("rep_order_id",orderId);
//            testRep.put("is_secode_service","0");
//            testRep.put("testCost",peopleCostJs);
            RepairTestReport testReport = new RepairTestReport();
            testReport.setId(IdWorker.getId());
            testReport.setRep_order_id(orderId);
            testReport.setIs_secode_service("0");
            testReport.setTestCost(peopleCostJs);
            int n =  client.insertTestReport(testReport);
            repOrder.setAll_cost(peopleCostJs);
        }else{
            productCost=   df.format(Float.valueOf(jso.getString("productCost")));
            prodcutComment = jso.getString("prodcutComment");
            float f= Float.valueOf(jso.getString("productCost"));
            float nf = Float.valueOf(jso.getString("peopleCost"));
            float ns =f +nf;
            repOrder.setAll_cost(df.format(ns));
            String all_cost = df.format(ns);
            Map<String,Object> parammap = client.getRepairPercentage();
            String cityS =  parammap.get("proportionCity").toString();
            String provinceS =  parammap.get("proportionProvince").toString();
            String platformS =  parammap.get("proportionPlatform").toString();
            double cityD = Double.valueOf(all_cost) * Double.valueOf(cityS) ;
            BigDecimal decimalCit = new BigDecimal(cityD);
            BigDecimal cityB = decimalCit.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            repOrder.setEarCity(cityB.toString());
            double provinceD = Double.valueOf(all_cost) * Double.valueOf(provinceS) ;
            BigDecimal decimalPro = new BigDecimal(provinceD);
            BigDecimal provinceB = decimalPro.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            repOrder.setEarProvince(provinceB.toString());
            double platformD = Double.valueOf(all_cost) * Double.valueOf(platformS) ;
            BigDecimal decimalPla = new BigDecimal(platformD);
            BigDecimal platformB = decimalPla.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            repOrder.setEarPlatform(platformB.toString());
            double n = Double.valueOf(all_cost) - cityD - provinceD - platformD ;
            BigDecimal decimal = new BigDecimal(n);
            BigDecimal setScale = decimal.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal coin =new BigDecimal(0.06).setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalCost = new BigDecimal(all_cost);
            BigDecimal all = decimalCost.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal porintSix = all.multiply(coin).setScale(2,BigDecimal.ROUND_HALF_DOWN);
            String earning = setScale.subtract(porintSix).setScale(2,BigDecimal.ROUND_HALF_DOWN).toString();
            repOrder.setTax(porintSix.toString());
            repOrder.setEarning(earning);
        }
        repOrder.setPeopleCost(peopleCostJs);
        repOrder.setProductCost(productCost);
        repOrder.setProdcutComment(prodcutComment);
        repOrder.setOrder_state("2");
        int n= client.updateRepOrder(repOrder);
        appOrder.setOrder_state("3");
        int m = appOrderClient.updateAppOrder(appOrder);
        if(n>0 && m>0){
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 判断是否有文件上传
            if (multipartResolver.isMultipart(request)){
                List<UploadInfo> list = null;
                try {
                    list = UploadUtil.uploadFiles(request,"","order/orderBillImg/"+orderId);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                for(UploadInfo info :list){
                    Map<String,Object> map = new HashMap<String, Object>();
                    map.put("id",IdWorker.getId());
                    map.put("rep_order_id",orderId);
                    map.put("img","https://www.zzzsyh.com/image/order/orderBillImg/"+orderId+"/"+info.getOldName());
                    map.put("create_time",new Date());
                    client.insertOrderBillImg(map);
                }
            }
            if("1".equals(type)){
                Map<String,Object> map =new HashMap<String, Object>();
                map.put("repOrderId",orderId);
                map.put("all_cost",peopleCostJs);
                HttpUtil.doPost("https://www.zzzsyh.com/cs_pay/sendTestBill",map);
            }else{
                Map<String,Object> map =new HashMap<String, Object>();
                map.put("repOrderId",orderId);
                HttpUtil.doPost("https://www.zzzsyh.com/cs_pay/sendBill",map);
            }
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("生成账单失败","002");
        }
    }

    @Override
    public Dto getRepProTypes(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        List<Map<String,Object>> list= client.getRepProTypes();
        if(EmptyUtils.isNotEmpty(list)){
            return  DtoUtil.returnDataSuccess(list);
        }else{
            return DtoUtil.returnFail("没有查到任何配件类型","002");
        }
    }

    @Override
    public Dto getRepProTypesById(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String typeId = request.getParameter("typeId");
        List<Map<String,Object>> list= client.getRepProTypesById(typeId);
        if(EmptyUtils.isNotEmpty(list)){
            return  DtoUtil.returnDataSuccess(list);
        }else{
            return DtoUtil.returnFail("没有查到任何配件类型","002");
        }
    }

    @Override
    public Dto ScanQrCode(HttpServletRequest request) {
        String qrCode = request.getParameter("qrCode");
        if(EmptyUtils.isNotEmpty(qrCode)){
            List<Map<String,Object>> list =  client.getQrHistoryByQrCode(qrCode);
            if(EmptyUtils.isNotEmpty(list)){
                return DtoUtil.returnDataSuccess(list);
            }else{
                return DtoUtil.returnFail("没有查到任何历史记录","002");
            }
        }else{
            return DtoUtil.returnFail("二维码编码为空","002");
        }
    }

    @Override
    public Dto createTestReport(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String dataStr = request.getParameter("data");
        Map<String,Object> testRep =  JSONObject.parseObject(dataStr);
        JSON json = (JSON) JSONObject.toJSON(dataStr);
        RepairTestReport testReport = JSON.toJavaObject(json ,RepairTestReport.class);
        String orderId  = testRep.get("rep_order_id").toString();
//        Map<String,Object> appOrder= repOrderMapper.getAppOrderInfoByRepId(orderId);
        RepOrder repOrder = client.getRepOrderById(orderId);
        AppOrder appOrder = appOrderClient.getAppOrderById(repOrder.getApp_order_id());
        if(EmptyUtils.isNotEmpty(appOrder)){
            if(EmptyUtils.isNotEmpty(appOrder.getIs_protect())){
                if("0".equals(appOrder.getIs_protect())){
                    String phone = appOrder.getUser_phone();
                    ClientUser clientUser = restClientUserClient.getClientUserByPhone(phone);
                    if(EmptyUtils.isEmpty(clientUser)){
                        return  DtoUtil.returnFail("客户未关注公众号，暂不能生成检测报告，请提醒客户使用手机号："+phone+"关注微信公众号","002");
                    }
                }
            }
            if("6".equals(appOrder.getOrder_state()) || "7".equals(appOrder.getOrder_state())){
                return  DtoUtil.returnFail("此订单已经取消，无法生成检测报告","002");
            }
        }else{
            return  DtoUtil.returnFail("没有找到此订单","002");
        }
        RepairTestReport hasTestReport = client.getTestReportByOrderId(orderId);
        if(EmptyUtils.isNotEmpty(hasTestReport)){
            return  DtoUtil.returnFail("此订单已经生成过检测报告，请勿重复生成","002");
        }
        String reportId = IdWorker.getId();
//        testRep.put("id",reportId);
        testReport.setId(reportId);
        int n =  client.insertTestReport(testReport);
        List<String> idList = new ArrayList<String>();
        if(n>0){
            JSONArray array = (JSONArray)testRep.get("products");
            if(EmptyUtils.isNotEmpty(array)){
                for(int m =0;m<array.size();m++){
                    String id = IdWorker.getId();
                    idList.add(id);
                    JSONObject js = array.getJSONObject(m);
                    RepProduct repProduct = new RepProduct();
                    repProduct.setId(id);
                    repProduct.setProduct_name(js.getString("name"));
                    repProduct.setProduct_model(js.getString("product_model"));
                    repProduct.setProduct_type_id(js.getString("type_id"));
                    repProduct.setType("1");
                    repProduct.setOrder_id(orderId);
//                    Map<String,Object> pro= new HashMap<String, Object>();
//                    pro.put("id",id);
//                    pro.put("product_name", js.get("name"));
//                    pro.put("product_type_id", js.get("type_id"));
//                    pro.put("product_model", js.get("product_model"));
//                    pro.put("count", js.get("count"));
//                    pro.put("type", "1");
//                    pro.put("order_id", orderId);
                    client.insertRepProduct(repProduct);
//                    repOrderMapper.insertRepProduct(pro);
                }
            }

            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 判断是否有文件上传
            if (multipartResolver.isMultipart(request)){
                List<UploadInfo> list = null;
                try {
                    list = UploadUtil.uploadFiles(request,"","order/testReportImg/"+testRep.get("rep_order_id").toString());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                for(UploadInfo info :list){
                    int m = Integer.valueOf(info.getKey().substring(0,1).toString())-1;
                    String id = idList.get(m);
                    Map<String,Object> map = new HashMap<String, Object>();
                    map.put("id",IdWorker.getId());
                    map.put("report_id",id);
                    map.put("imageUrl","https://www.zzzsyh.com/image/order/testReportImg/"+testRep.get("rep_order_id").toString()+"/"+info.getOldName());
//                    repOrderMapper.insertReportImg(map);
                    client.insertRepImg(map);
                }
            }

            Map<String,Object> map =new HashMap<String, Object>();
            map.put("reportId",reportId);
            HttpUtil.doPost("https://www.zzzsyh.com/cs_pay/sendTestReport",map);


            RepOrder reporder =client.getRepOrderById(testRep.get("rep_order_id").toString());
            reporder.setOrder_state("1");
            client.updateRepOrder(repOrder);
            AppOrder appOrder1 = appOrderClient.getAppOrderById(reporder.getApp_order_id());
            appOrder1.setOrder_state("2");
            appOrderClient.updateAppOrder(appOrder1);
//            orderMap.put("id",testRep.get("rep_order_id").toString());
//            orderMap.put("order_state","1");
//            repOrderMapper.updateMapOrder(orderMap);
//            Map<String,Object> appMap = new HashMap<String, Object>();
//            appMap.put("id",orderMap.get("app_order_id"));
//            appMap.put("order_state","2");
//            appOrderMapper.updateAppOrderMap(appMap);
            return  DtoUtil.returnDataSuccess(testRep);
        }
        else{
            return  DtoUtil.returnFail("生成检测报告失败","002");
        }
    }

    @Override
    public Dto getTestReportById(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String orderId = request.getParameter("orderId");
        RepairTestReport testReport = client.getTestReportByOrderId(orderId);
        if(EmptyUtils.isNotEmpty(testReport)){
            List<Map<String,Object>> images = client.getTestReportImgsById(testReport.getId());
            testReport.setImages(images);
            Map<String,Object> param = new HashMap<String, Object>();
            param.put("orderId",orderId);
            param.put("type","1");
            List<RepProduct> pros = client.getRepProsByOrderId(param);
            testReport.setProducts(pros);
            return DtoUtil.returnDataSuccess(testReport);
        }else{
            return  DtoUtil.returnFail("没有此检测报告","002");
        }
    }

    @Override
    public Dto getBillById(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String orderId = request.getParameter("orderId");
        Map<String,Object> bill = new HashMap<String, Object>();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("orderId",orderId);
        param.put("type","2");
        List<RepProduct> pros = client.getRepProsByOrderId(param);
        List<Map<String,Object>> imgs = client.getBillOrderImg(orderId);
        RepOrder order = client.getRepOrderById(orderId);
//        orderMap.put("proCost",Double.valueOf(orderMap.get("all_cost").toString()) -   Double.valueOf(orderMap.get("peopleCost").toString()));
        order.setProductCost(String.valueOf(Double.valueOf(order.getAll_cost()) -   Double.valueOf(order.getPeopleCost())));
        bill.put("earning",order.getEarning());
        bill.put("products",pros);
        bill.put("order",order);
        bill.put("imgs",imgs);
        return DtoUtil.returnDataSuccess(bill);
    }

    @Override
    public Dto getHbRepOrderList(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String type = request.getParameter("type");
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("userId",user.getId());
        if(EmptyUtils.isNotEmpty(type)){
            param.put("type",type);
        }
        List<Map<String,Object>> orderList = client.getHbRepOrderList(param);

        if(EmptyUtils.isNotEmpty(orderList)){
            return DtoUtil.returnDataSuccess(orderList);
        }else{
            return DtoUtil.returnFail("没有找到相关订单","002");
        }
    }

    @Override
    public Dto delRepProduct(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if (EmptyUtils.isEmpty(user)) {
            return DtoUtil.returnFail("用户未登录", "0001");
        }
//        data={"orderId":"001","products":[{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"},{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"},{"price":"253","type_id":"12313","count":"2","name":"波片","productId":"1321"}]}
        String data = request.getParameter("data");
        JSONObject jso = JSONObject.parseObject(data);
        JSONArray array = jso.getJSONArray("products");
        JSONArray updateArray = jso.getJSONArray("up_products");
        String orderId = jso.get("orderId").toString();
//        Map<String, Object> orderMap = client.getRepMapById(orderId);
        RepOrder repOrder = client.getRepOrderById(orderId);
//        Map<String, Object> appOrderMap = repOrderMapper.getAppOrderInfoByRepId(orderMap.get("id").toString());
       AppOrder appOrder = appOrderClient.getAppOrderById(repOrder.getApp_order_id());
        if (EmptyUtils.isNotEmpty(updateArray)) {
            for (int n = 0; n < updateArray.size(); n++) {
                JSONObject js = updateArray.getJSONObject(n);
                RepProduct repProduct = new RepProduct();
                repProduct.setId(IdWorker.getId());
                repProduct.setProduct_name(js.getString("name"));
                repProduct.setProduct_type_id(js.getString("type_id"));
                if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                    repProduct.setQrcode(js.getString("qrcode"));
                }
                repProduct.setProduct_model(js.getString("product_model"));
                repProduct.setCount(js.getString("count"));
                repProduct.setType("2");
                repProduct.setOrder_id(orderId);
                client.insertRepProduct(repProduct);

                QrHistory qrHistory = new QrHistory();
                qrHistory.setId(IdWorker.getId());
                qrHistory.setNode_code("gh");
                qrHistory.setOperation("损坏更换");
                qrHistory.setOperation_user_id(user.getId());
                qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                    qrHistory.setQrcode(js.getString("qrcode"));
                    client.insertQrHistory(qrHistory);
                }
            }
        }
        if (EmptyUtils.isNotEmpty(array)) {
            if (EmptyUtils.isNotEmpty(appOrder.getFixed_price())) {
                if (!"0.00".equals(appOrder.getFixed_price())) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject js = array.getJSONObject(i);
                        RepProduct repProduct = new RepProduct();
                        repProduct.setId(IdWorker.getId());
                        repProduct.setProduct_name(js.getString("name"));
                        repProduct.setProduct_type_id(js.getString("type_id"));
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            repProduct.setQrcode(js.getString("qrcode"));
                        }
                        repProduct.setProduct_model(js.getString("product_model"));
                        repProduct.setCount(js.getString("count"));
                        repProduct.setType("2");
                        repProduct.setOrder_id(orderId);
                        client.insertRepProduct(repProduct);
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            QrHistory qrHistory = new QrHistory();
                            qrHistory.setId(IdWorker.getId());
                            qrHistory.setQrcode(js.getString("qrcode"));
                            qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_code("az");
                            qrHistory.setOperation("安装");
                            qrHistory.setOperation_user_id(user.getId());
                            client.insertQrHistory(qrHistory);
                        }
                    }
                } else {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject js = array.getJSONObject(i);
                        RepProduct repProduct = new RepProduct();
                        repProduct.setId(IdWorker.getId());
                        repProduct.setProduct_name(js.getString("name"));
//                        repProduct.setProduct_price(js.get("price").toString());
                        repProduct.setProduct_name(js.getString("name"));
                        repProduct.setProduct_type_id(js.getString("type_id"));
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            repProduct.setQrcode(js.getString("qrcode"));
                        }
                        repProduct.setProduct_model(js.getString("product_model"));
                        repProduct.setCount(js.getString("count"));
                        repProduct.setType("2");
                        repProduct.setOrder_id(orderId);
                        client.insertRepProduct(repProduct);
                        if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                            QrHistory qrHistory = new QrHistory();
                            qrHistory.setId(IdWorker.getId());
                            qrHistory.setQrcode(js.getString("qrcode"));
                            qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                            qrHistory.setNode_code("az");
                            qrHistory.setOperation("安装");
                            qrHistory.setOperation_user_id(user.getId());
                            client.insertQrHistory(qrHistory);
                        }
                    }
                }
            } else {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject js = array.getJSONObject(i);
                    RepProduct repProduct = new RepProduct();
                    repProduct.setId(IdWorker.getId());
                    repProduct.setProduct_name(js.getString("name"));
//                    repProduct.setProduct_price(js.get("price").toString());
                    repProduct.setProduct_name(js.getString("name"));
                    repProduct.setProduct_type_id(js.getString("type_id"));
                    if(EmptyUtils.isNotEmpty(js.get("qrcode"))){
                        repProduct.setQrcode(js.getString("qrcode"));
                    }
                    repProduct.setProduct_model(js.getString("product_model"));
                    repProduct.setCount(js.getString("count"));
                    repProduct.setType("2");
                    repProduct.setOrder_id(orderId);
                    if (EmptyUtils.isNotEmpty(js.get("qrcode"))) {
                        QrHistory qrHistory = new QrHistory();
                        qrHistory.setId(IdWorker.getId());
                        qrHistory.setQrcode(js.getString("qrcode"));
                        qrHistory.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        qrHistory.setNode_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                        qrHistory.setNode_code("az");
                        qrHistory.setOperation("安装");
                        qrHistory.setOperation_user_id(user.getId());
                        client.insertQrHistory(qrHistory);
                    }
                }
            }

        }
        return DtoUtil.returnSuccess();
    }

    @Override
    public Dto getRepOrderEvlById(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(EmptyUtils.isEmpty(user)){
            return DtoUtil.returnFail("用户未登录","001");
        }
        String orderId = request.getParameter("orderId");
        Map<String,Object> map = client.getRepOrderEvlById(orderId);
        if(EmptyUtils.isNotEmpty(map)){
            return DtoUtil.returnDataSuccess(map);
        }else{
            return DtoUtil.returnFail("没有评价","002");
        }
    }


    @Override
    public Dto getWxTestReportById(String orderId) throws Exception {
        RepairTestReport report = client.getTestReportByOrderId(orderId);
        if(EmptyUtils.isNotEmpty(report)){
//            List<Map<String,Object>> images = repOrderMapper.getTestReportImgsById(report.get("id").toString());
            List<Map<String,Object>> orderDetails = client.getOrderDetailsByOrderId(orderId, "1");
            for(Map<String,Object> a:orderDetails){
                String id = a.get("id").toString();
                List<Map<String,Object>> images = client.getTestReportImgsById(id);
                a.put("images", images);
            }
            report.setOrderDetails(orderDetails);
            return DtoUtil.returnDataSuccess(report);
        }else{
            return  DtoUtil.returnFail("没有此检测报告","002");
        }
    }

    @Override
    public Map<String,Object> getRepairPercentage() throws  Exception{
        return client.getRepairPercentage();
    }

    @Override
    public Integer updateRepairPercentage(Map<String,Object> map) throws  Exception{
        return client.updateRepairPercentage(map);
    }

    @Override
    public Dto getOrderInvoiceByUserId(HttpServletRequest request) throws Exception{
        String userId = request.getParameter("userId");
//        String userId = "630175780864790528";
        ClientUser map =  restRepairOrderClient.getClientUserById(Long.valueOf(userId));
        List<Map<String, Object>> list = client.getOrderInvoiceByUserId(userId, map.getPhone());
        return DtoUtil.returnSuccess("获取成功", list);
    }

    @Override
    public void updateOrderByIds(String params) throws Exception{
        client.updateOrderByIds(params.split(","));
    }

    @Override
    public Dto getOrderInvoiceByUserPId(HttpServletRequest request) throws Exception{
        String userId = request.getParameter("factoryId");
        List<Map<String, Object>> list = client.getOrderInvoiceByUserPId(userId);
        return DtoUtil.returnSuccess("获取成功", list);
    }

}
